package cn.chongqing.han.toolkit.net;

import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Han Hui Long on 2018/6/1 9:30.
 */

public class NetConnUtil {
    private static final MediaType CONTENT_JSON = MediaType.parse("application/json");
    private static final MediaType CONTENT_WWW_FORM = MediaType.parse("application/x-www-form-urlencoded");
    private static final MediaType CONTENT_FORM = MediaType.parse("multipart/form-data");

    private static OkHttpClient HTTP_CLIENT;
    private final static boolean enableUrlEncoding = false;

    static {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        HTTP_CLIENT = clientBuilder
//                .connectTimeout()
//                .readTimeout()
//                .sslSocketFactory()
                .build();
    }

    public static void get(String url, Callback callback) {
        Request.Builder requestBuilder = new Request.Builder();
        addCommonHeader(requestBuilder);
        Request request = requestBuilder.url(url).build();
        Call call = HTTP_CLIENT.newCall(request);
        call.enqueue(callback);
    }

    public static void get(String url, RequestParam getParam, Callback callback) {
        Request.Builder requestBuilder = new Request.Builder();
        addCommonHeader(requestBuilder);
        Request request = requestBuilder.url(getUrlWithQueryString(enableUrlEncoding, url, getParam)).build();
        Call call = HTTP_CLIENT.newCall(request);
        call.enqueue(callback);
    }

    public static void post(String url, String json, Callback callback) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder theBuilder = new Request.Builder();
        addCommonHeader(theBuilder);
        RequestBody body = RequestBody.create(CONTENT_JSON, json);
        Request request = theBuilder
                .url(url)
                .post(body)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public static void postForm(String url, Map<String, String> param, Callback callback) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder();
        addCommonHeader(requestBuilder);

        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        RequestBody formBody = builder.build();

        Request request = requestBuilder.url(url).post(formBody).build();
        Call theCall = mOkHttpClient.newCall(request);
        theCall.enqueue(callback);
    }


    private static void addCommonHeader(Request.Builder requestBuilder) {

    }


    private static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParam params) {
        if (url == null)
            return null;

        if (shouldEncodeUrl) {
            try {
                String decodedURL = URLDecoder.decode(url, "UTF-8");
                URL _url = new URL(decodedURL);
                URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef());
                url = _uri.toASCIIString();
            } catch (Exception ex) {
                // Should not really happen, added just for sake of validity
//                log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
            }
        }

        if (params != null) {
            // Construct the query string and trim it, in case it
            // includes any excessive white spaces.
            String paramString = params.toString().trim();
            if (!paramString.equals("") && !paramString.equals("?")) {
                url += url.contains("?") ? "&" : "?";
                url += paramString;
            }
        }
        return url;
    }


}
